package cn.ac.cintcm.synonymous;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.HashMap;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class OracleDb {
    private static HashMap<String, String> dbConfig;
    private static final String CONFIGSPILITOR = "=";
    
    private static void loadConfig() throws IOException, NamingException {
        Context c = new InitialContext();
        String path = (String)c.lookup("java:comp/env/syn/home");
        //String path = System.getProperty("syn.syn.home");
        System.out.println("syn.home:" + path);
        if (path == null) {
            path = System.getProperty("user.dir");
        }
        System.out.println("path:" + path);
        File inputFile = new File(path, "config.txt");
        
        BufferedReader reader = new BufferedReader(new FileReader(inputFile));
        dbConfig = new HashMap<String, String>();
        String line = reader.readLine();
        while (line != null) {
            String[] name = getEntry(line);
            if (name != null && name.length == 2) {
                dbConfig.put(name[0].trim(), name[1].trim());
            }
            line = reader.readLine();
        }
        reader.close();
    }
    
    private static String[] getEntry(String line) {
        String[] items = null;
        if (line != null) {
            items =line.split(CONFIGSPILITOR);
        }
        return items;
    }

    public static Connection getConnection() {
        try {
            loadConfig();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NamingException e) {
            e.printStackTrace();
        }
        String url = (String) dbConfig.get("url");
        String userName = (String) dbConfig.get("user");
        String password = (String) dbConfig.get("password");
        Connection conn = null;
        try {
            DriverManager.registerDriver (new oracle.jdbc.driver.OracleDriver());
            conn = DriverManager.getConnection(url, userName, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }
}
